//$URL: http://dasding.googlecode.com/svn/branches/spring-security/api/src/main/java/de/piratech/dasding/security/CustomAuthenticationManager.java $
//$Id: CustomAuthenticationManager.java 74 2012-10-22 18:17:47Z amuthmann@gmail.com $
package de.piratech.dasding.security;

import de.piratech.dasding.data.User;
import de.piratech.dasding.data.database.Database;
import de.piratech.dasding.data.helper.PasswordHelper;
import javax.ws.rs.ext.Provider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 */
public class CustomAuthenticationManager implements AuthenticationManager {

  @Autowired
  private Database database;

  public Authentication authenticate(Authentication auth) throws AuthenticationException {

    User user = database.getUserData().getUser(auth.getName());

    if (StringUtils.equals(PasswordHelper.getCryptedPassword((String) auth.getCredentials(), auth.getName()), user.getPassword())) {
      return new UsernamePasswordAuthenticationToken(user, auth.getCredentials(), auth.getAuthorities());
    }
    return new UsernamePasswordAuthenticationToken(user, auth.getCredentials());
  }
}
